package com.jthinker.web.controller.front;

import com.jthinker.bean.enu.Operator;
import com.jthinker.bean.vo.Condition;
import com.jthinker.bean.vo.QueryResult;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.service.CategoryService;
import com.jthinker.service.PostService;
import com.jthinker.web.controller.common.BaseController;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/4/19 14:05
 */
@Controller
public class IndexController extends BaseController
{
    @Resource
    private PostService postService;

    @Resource
    private CategoryService categoryService;

    @RequestMapping({ "/index", "/" })
    public String index(HttpServletRequest request, Model model)
    {
        SearchFilter filter = getSearchFilter(request);
        List<Map<String, Object>> categorys = categoryService.findTree();
        QueryResult<Map<String, Object>> result = postService.queryList(filter);
        model.addAttribute("result", result);
        model.addAttribute("categorys", categorys);
        return "index/index";
    }

    @RequestMapping("/cat/{category}")
    public String view(@PathVariable("category") String category, HttpServletRequest request, Model model)
    {
        SearchFilter filter = getSearchFilter(request);
        if (StringUtils.isNotBlank(category))
        {
            Long categoryId = categoryService.findBySlug(category);

            if (categoryId != null)
            {
                filter.getWhere().add(new Condition("category_id", String.valueOf(categoryId), Operator.EQUAL));
            }
        }

        List<Map<String, Object>> categorys = categoryService.findTree();
        QueryResult<Map<String, Object>> result = postService.queryList(filter);
        model.addAttribute("result", result);
        model.addAttribute("categorys", categorys);
        return "index/index";
    }

    @RequestMapping("/post/{id}")
    public String viewArticle(@PathVariable("id") String id, HttpServletResponse response, Model model)
    {
        if (StringUtils.isBlank(id))
        {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }

        Map<String, Object> post = postService.read(id);
        if (MapUtils.isEmpty(post))
        {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }

        model.addAttribute("post", post);

        return "post/post";
    }

}
